<template>
  <view class="exception-report-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-red" :isBack="true">
      <block slot="content">异常上报</block>
      <block slot="right">
        <text class="cuIcon-check" @click="submitReport"></text>
      </block>
    </cu-custom>

    <!-- 表单内容 -->
    <view class="form-container">
      <!-- 基本信息 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">基本信息</text>
        </view>
        <view class="form-content padding">
          <view class="form-item margin-bottom">
            <text class="form-label required">异常标题</text>
            <input v-model="reportForm.title" 
                   placeholder="请输入异常标题" 
                   class="form-input" />
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label required">异常类型</text>
            <picker :range="exceptionTypes" 
                    :value="selectedTypeIndex"
                    @change="onTypeChange">
              <view class="form-picker">
                {{ reportForm.type || '请选择异常类型' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label required">异常等级</text>
            <picker :range="levelOptions" 
                    range-key="label"
                    :value="selectedLevelIndex"
                    @change="onLevelChange">
              <view class="form-picker">
                {{ reportForm.level ? (levelOptions[selectedLevelIndex] && levelOptions[selectedLevelIndex].label) : '请选择异常等级' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">相关设备</text>
            <picker :range="equipmentOptions" 
                    range-key="name"
                    :value="selectedEquipmentIndex"
                    @change="onEquipmentChange">
              <view class="form-picker">
                {{ reportForm.equipmentId ? (equipmentOptions[selectedEquipmentIndex] && equipmentOptions[selectedEquipmentIndex].name) : '请选择设备' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
        </view>
      </view>

      <!-- 异常描述 -->
      <view class="form-section bg-white margin-top">
        <view class="section-header padding">
          <text class="section-title">异常描述</text>
        </view>
        <view class="form-content padding">
          <view class="form-item margin-bottom">
            <text class="form-label required">异常描述</text>
            <textarea v-model="reportForm.description" 
                      placeholder="请详细描述异常情况" 
                      class="form-textarea"></textarea>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">发生时间</text>
            <picker mode="datetime" 
                    :value="reportForm.occurTime" 
                    @change="onOccurTimeChange">
              <view class="form-picker">
                {{ reportForm.occurTime || '请选择发生时间' }}
                <text class="cuIcon-right"></text>
              </view>
            </picker>
          </view>
          
          <view class="form-item margin-bottom">
            <text class="form-label">影响范围</text>
            <textarea v-model="reportForm.impact" 
                      placeholder="请描述异常对生产的影响" 
                      class="form-textarea small"></textarea>
          </view>
        </view>
      </view>

      <!-- 附件上传 -->
      <view class="form-section bg-white margin-top margin-bottom">
        <view class="section-header padding">
          <text class="section-title">附件上传</text>
        </view>
        <view class="form-content padding">
          <view class="upload-area" @click="chooseImage">
            <view v-if="reportForm.images.length === 0" class="upload-placeholder">
              <text class="cuIcon-add upload-icon"></text>
              <text class="upload-text">点击上传图片</text>
            </view>
            <view v-else class="image-list">
              <view v-for="(image, index) in reportForm.images" :key="index" 
                    class="image-item">
                <image :src="image" class="uploaded-image"></image>
                <text class="cuIcon-close delete-btn" @click.stop="deleteImage(index)"></text>
              </view>
              <view v-if="reportForm.images.length < 5" class="add-more" @click.stop="chooseImage">
                <text class="cuIcon-add"></text>
              </view>
            </view>
          </view>
          <view class="upload-tip text-sm text-gray margin-top">
            最多可上传5张图片，支持jpg、png格式
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="cu-btn bg-gray margin-right" @click="saveDraft">保存草稿</button>
      <button class="cu-btn bg-red" @click="submitReport">提交上报</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      reportForm: {
        title: '',
        type: '',
        level: '',
        equipmentId: '',
        description: '',
        occurTime: '',
        impact: '',
        images: []
      },
      exceptionTypes: ['设备故障', '质量问题', '安全隐患', '材料缺失', '工艺异常', '其他'],
      selectedTypeIndex: 0,
      levelOptions: [
        { label: '低级', value: 'low' },
        { label: '中级', value: 'medium' },
        { label: '高级', value: 'high' }
      ],
      selectedLevelIndex: 0,
      equipmentOptions: [],
      selectedEquipmentIndex: 0
    }
  },

  onLoad() {
    this.loadEquipments()
    this.initTime()
  },

  methods: {
    loadEquipments() {
      // 模拟设备数据
      this.equipmentOptions = [
        { id: 1, name: '切割机-001' },
        { id: 2, name: '组装台-002' },
        { id: 3, name: '检测设备-003' }
      ]
    },

    initTime() {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hour = String(now.getHours()).padStart(2, '0')
      const minute = String(now.getMinutes()).padStart(2, '0')
      this.reportForm.occurTime = `${year}-${month}-${day} ${hour}:${minute}`
    },

    onTypeChange(e) {
      this.selectedTypeIndex = e.detail.value
      this.reportForm.type = this.exceptionTypes[e.detail.value]
    },

    onLevelChange(e) {
      this.selectedLevelIndex = e.detail.value
      this.reportForm.level = this.levelOptions[e.detail.value].value
    },

    onEquipmentChange(e) {
      this.selectedEquipmentIndex = e.detail.value
      this.reportForm.equipmentId = this.equipmentOptions[e.detail.value].id
    },

    onOccurTimeChange(e) {
      this.reportForm.occurTime = e.detail.value
    },

    chooseImage() {
      uni.chooseImage({
        count: 5 - this.reportForm.images.length,
        sizeType: ['compressed'],
        sourceType: ['camera', 'album'],
        success: (res) => {
          this.reportForm.images = this.reportForm.images.concat(res.tempFilePaths)
        }
      })
    },

    deleteImage(index) {
      this.reportForm.images.splice(index, 1)
    },

    validateForm() {
      if (!this.reportForm.title.trim()) {
        uni.showToast({
          title: '请输入异常标题',
          icon: 'none'
        })
        return false
      }

      if (!this.reportForm.type) {
        uni.showToast({
          title: '请选择异常类型',
          icon: 'none'
        })
        return false
      }

      if (!this.reportForm.level) {
        uni.showToast({
          title: '请选择异常等级',
          icon: 'none'
        })
        return false
      }

      if (!this.reportForm.description.trim()) {
        uni.showToast({
          title: '请输入异常描述',
          icon: 'none'
        })
        return false
      }

      return true
    },

    async submitReport() {
      if (!this.validateForm()) return

      try {
        uni.showLoading({ title: '提交中...' })
        
        // 模拟提交
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '上报成功',
            icon: 'success'
          })
          
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        }, 2000)
        
      } catch (error) {
        console.error('提交失败:', error)
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        })
      }
    },

    async saveDraft() {
      try {
        uni.showLoading({ title: '保存中...' })
        
        // 模拟保存草稿
        setTimeout(() => {
          uni.hideLoading()
          uni.showToast({
            title: '草稿保存成功',
            icon: 'success'
          })
        }, 1000)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: '保存失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.exception-report-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

.form-section {
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin: 0 24rpx;
  
  .section-header {
    border-bottom: 1rpx solid #f0f0f0;
    
    .section-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .form-item {
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      margin-bottom: 16rpx;
      
      &.required::after {
        content: '*';
        color: #f5222d;
        margin-left: 4rpx;
      }
    }
    
    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
    
    .form-textarea {
      width: 100%;
      min-height: 120rpx;
      padding: 16rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      resize: none;
      
      &.small {
        min-height: 80rpx;
      }
    }
    
    .form-picker {
      height: 80rpx;
      padding: 0 24rpx;
      border: 1rpx solid #d9d9d9;
      border-radius: 8rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #333;
    }
  }
}

.upload-area {
  border: 2rpx dashed #d9d9d9;
  border-radius: 8rpx;
  min-height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .upload-placeholder {
    text-align: center;
    color: #999;
    
    .upload-icon {
      font-size: 60rpx;
      margin-bottom: 16rpx;
    }
    
    .upload-text {
      font-size: 28rpx;
    }
  }
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    padding: 16rpx;
    
    .image-item {
      position: relative;
      width: 120rpx;
      height: 120rpx;
      
      .uploaded-image {
        width: 100%;
        height: 100%;
        border-radius: 8rpx;
      }
      
      .delete-btn {
        position: absolute;
        top: -8rpx;
        right: -8rpx;
        width: 32rpx;
        height: 32rpx;
        background-color: #f5222d;
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20rpx;
      }
    }
    
    .add-more {
      width: 120rpx;
      height: 120rpx;
      border: 2rpx dashed #d9d9d9;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999;
      font-size: 40rpx;
    }
  }
}

.upload-tip {
  text-align: center;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  gap: 24rpx;
  
  .cu-btn {
    flex: 1;
  }
}
</style>
